package com.auxgroup.smarthome.enterprise.utils;

import com.auxgroup.smarthome.enterpriseapi.responsebody.MetaBean;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.List;

/**
 * Created by kevinchen on 2017/6/14.
 * 平台的分页 与 jpa的分页的转换
 */
public class PageableUtils {

    public static <T> Page<T> changePage(MetaBean metaBean, List<T> objects){
        if (metaBean==null){
            metaBean = new MetaBean();
        }
        int size = metaBean.getLimit();
        int page = metaBean.getSkip()/metaBean.getLimit();
        Pageable pageable = new PageRequest(page,size);
        return new PageImpl<T>(objects,pageable,metaBean.getTotal());
    }

    /**
     * 转换为适应平台的分页方式
     * @param pageable
     * @return
     */
    public static Pair<Integer, Integer> changePageable(Pageable pageable) {
        int skip = pageable.getPageNumber()*pageable.getPageSize();
        int limit = pageable.getPageSize();
        return Pair.of(skip, limit);
    }

}
